package org.zh.util.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.function.Function;

public class ProxyFactory {
    // 工厂方法：创建代理（内部可复用处理器）
    public static <T> T createProxy(Class<T> interfaceClass, Function<Method, Object> methodHandler) {
        InvocationHandler handler = new DynamicInvocationHandler(methodHandler);
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class<?>[]{interfaceClass},
                handler
        );
    }

    // 动态处理器
    private static class DynamicInvocationHandler implements InvocationHandler {
        private final Function<Method, Object> methodHandler;

        public DynamicInvocationHandler(Function<Method, Object> methodHandler) {
            this.methodHandler = methodHandler;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return methodHandler.apply(method);
        }
    }
}
